<?php
namespace adminmatrix\server\app\middleware;
use adminmatrix\server\app\lists\BaseListsData;
use think\Model;
use think\model\Collection;
use think\Response;
use think\facade\Db;
class ReturnMiddleware
{

   public function handle($request , \Closure $next){

        // 执行下一个中间件或控制器
        $response = $next($request);
        // 获取响应数据

        $result = false;
        $data = [
            'code'      =>  $response->getCode(),
            'message'   =>  '',
        ];
        if ($response->getData() instanceof  Model){

        } else if($this->isModel($response->getData())){

        } else if($response->getData() instanceof  Collection)
        {
            $result = true;
            $data['data']   =  $model =  $response->getData();
            $data['test']   =   $model->fetchSql(true);
        } else if(is_array($response->getData()))
        {

        }else{
            $parentClass = @class_parents($response->getData());

            // 判断是否是 BaseListsData 类的实例
            if (isset($parentClass[BaseListsData::class]))
            {
                $result = true;
                if (is_array($response->getData()->lists()))
                {
                    $data['data']   =  [
                        'lists'     =>  $response->getData()->lists(),
                    ];
                }else{
                    $parentClass = @class_parents($response->getData()->lists());


                    $data['data']   =  [
                        'lists'     =>  $response->getData()->lists()->select()->toArray(),
                    ];



                    if (env('app_debug'))
                    {
                        $data['sql'] =  Db::getLastSql();
                    }


                }
                $data['data']['total']      =  (int) $response->getData()->count();
                $data['data']['current']       = $response->getData()->pageNo;
                $data['data']['pageSize']   = $response->getData()->pageSize;

            }
        }


        $request->asd =123;

        if ($result)
        {
            return Response::create([...$data,
                'response_time' =>  time()
            ] , 'json');
        }

        return $response;

   }

   protected function isModel($object)
   {
       return $object instanceof  Model;
   }
}